#include "stdafx.h"
#include "net/NTPClient.hpp"
#include "net/DatagramSocket.hpp"


NET_NAMESPACE_BEGIN

CNTPClient::CNTPClient(CIPAddress::Family family, int timeout) : m_family(family), m_timeout(timeout)
{
}

CNTPClient::~CNTPClient()
{
}

int CNTPClient::request(const std::string& address) const
{
	CSocketAddress addr(address, 123);
	return request(addr);
}

int CNTPClient::request(CSocketAddress& address) const
{
	CSocketAddress sa;
	CDatagramSocket ntpSocket(m_family);
	ntpSocket.setReceiveTimeout(m_timeout);
	ntpSocket.bind(sa);

	CSocketAddress returnAddress;

	CNTPEventArgs eventArgs(address);

	CNTPPacket packet;
	UInt8 p[1024];
	packet.packet(&p[0]);

	ntpSocket.sendTo(p, 48, address);

	int received = 0;
	try
	{
		CSocketAddress sender;
		int n = ntpSocket.receiveFrom(p, sizeof(p)-1, sender);

		if (n < 48) // NTP packet must have at least 48 bytes
			throw NTPException("Invalid response received");

		packet.setPacket(p);
		eventArgs.setPacket(packet);
		++received;
		response.notify(this, eventArgs);
	}
	catch (TimeoutException &)
	{
		// ignore
	}

	return received;
}


NET_NAMESPACE_END
